// TODO roolup引用方式,待测试
// import Handsontable from "../../../lib/tmp/index.mjs";
import Handsontable from "../../../lib/tmp";
import { FontStyleEnum } from "./HandSonGridToolService/enum";
import { defaultCellStyle } from "../HandSonGrid";
import BigNumber from "bignumber.js";
/**
 * 通用渲染逻辑
 * 暂时未找到继承根渲染器的方式，先用通用函数进行代替
 * 通用函数只用来处理样式相关的通用逻辑，value格式化交给具体的渲染器去处理
 */
function commonRender(instance, td, row, col, prop, value, cellProperties) {
    // const cellMeta = instance.getCellMeta(row, col);
    const cellMeta = cellProperties;
    let fc = defaultCellStyle.fc;
    let bg = defaultCellStyle.bg;
    // 文字颜色
    if (cellMeta["custom"] && cellMeta["custom"]["fc"]) {
        fc = cellMeta["custom"]["fc"];
    }
    if (cellMeta["custom"] && cellMeta["custom"]["bg"]) {
        bg = cellMeta["custom"]["bg"];
    }
    td.style.color = `${fc}`;
    td.style.backgroundColor = `${bg}`;
    //文本加粗
    if (cellMeta["custom"] && cellMeta["custom"]["bl"]) {
        const bl = cellMeta["custom"]["bl"];
        if (bl === 1) {
            td.className = td.className.replace("cpas-bold", "");
        }
        else {
            td.className = td.className + " cpas-bold";
        }
    }
    //文本样式(字形)
    if (cellMeta["custom"] && cellMeta["custom"]["it"]) {
        const it = cellMeta["custom"]["it"];
        if (it === FontStyleEnum.normal) {
            td.className = td.className.replace("cpas-font-style", "");
        }
        else {
            td.className = td.className + " cpas-font-style";
        }
    }
    //对齐方式
    if (cellMeta["custom"] && cellMeta["custom"]["ht"]) {
        const ht = cellMeta["custom"]["ht"];
        if (ht === 3) {
            td.className = td.className + " cpas_table cpas-text-right";
        }
        else if (ht === 2) {
            td.className = td.className + " cpas_table cpas-text-center";
        }
        else {
            td.className = td.className + " cpas_table cpas-text-left";
        }
    }
    else {
        //默认文本，数字右对齐
        if (cellMeta.type === "numeric") {
            td.className = td.className + " cpas_table cpas-text-right";
        }
        else {
            td.className = td.className + " cpas_table cpas-text-left";
        }
    }
    //公式标记逻辑
    const isMarkFormula = instance.ref?.tableConfig?.formulaMark || false;
    //单元格原值
    const sourceCellData = instance.getSourceDataAtCell(row, col);
    //表格类型
    const type = instance.ref?.props.type;
    let isCustomFormula = false;
    let isExcelFormula = false;
    const customFormula = ["FS_CELL", "CP_CELL", "IN_CELL"];
    if (sourceCellData &&
        typeof sourceCellData === "string" &&
        sourceCellData.startsWith("=")) {
        //如果公式字符串中包含customFormula中的任意一个，就认为是自定义公式
        isCustomFormula = customFormula.some((formula) => {
            return sourceCellData.includes(formula);
        });
        if (!isCustomFormula) {
            isExcelFormula = true;
        }
    }
    if (type !== "zl") {
        // 期间类型标记
        if (cellMeta["timeColumn"] && row !== 0 && col !== 0) {
            if (!isMarkFormula && type !== "fs") {
                td.className = td.className + " cpas-formula-normal-mark";
            }
            else if (isMarkFormula) {
                const mainKey = cellMeta["timeColumn"].mainKey;
                // 标记期间类型母列
                const columnKey = cellMeta["columnKey"];
                if (columnKey.startsWith(mainKey)) {
                    td.className = td.className + " cpas-main-column-mark";
                }
                else {
                    td.className = td.className + " cpas-period-type-mark";
                }
            }
        }
        //判断当前单元格是否为匹配的行列，兼容旧模板写法. 旧模板 公式行不会有 matchDynamic
        let isFormulaMatchDynamic = false;
        if (cellMeta.formula) {
            isFormulaMatchDynamic =
                instance.ref?.logicFormulaService.isMatchDynamicPosition(row, col, cellMeta.formula);
        }
        //动态行列标注
        if ((cellMeta["isDynamic"] &&
            cellMeta["matchDynamic"] &&
            row !== 0 &&
            col !== 0) ||
            (cellMeta.formula && cellMeta["matchDynamic"]) ||
            isFormulaMatchDynamic === true) {
            if (!isMarkFormula && type !== "fs") {
                td.className = td.className + " cpas-formula-normal-mark";
            }
            else if (isMarkFormula) {
                td.className = td.className + " cpas-dynamic-mark";
            }
        }
        //excel公式标注
        if (isExcelFormula && row !== 0 && col !== 0) {
            if (!isMarkFormula && type !== "fs") {
                td.className = td.className + " cpas-formula-normal-mark";
            }
            else if (isMarkFormula) {
                td.className = td.className + " cpas-excel-formula-mark";
            }
        }
        //单元格取数标注
        if (isCustomFormula && row !== 0 && col !== 0) {
            if (!isMarkFormula && type !== "fs") {
                td.className = td.className + " cpas-formula-normal-mark";
            }
            else if (isMarkFormula) {
                td.className = td.className + " cpas-cell-get-mark";
            }
        }
        //聚合运算标注
        if (((cellMeta["r_polymeric"] &&
            !cellMeta["p_exclude"] &&
            !cellMeta["c_exclude"]) ||
            (cellMeta["c_polymeric"] &&
                !cellMeta["p_exclude"] &&
                !cellMeta["c_exclude"])) &&
            row !== 0 &&
            col !== 0) {
            if (!isMarkFormula && type !== "fs") {
                td.className = td.className + " cpas-formula-normal-mark";
            }
            else if (isMarkFormula) {
                td.className = td.className + " cpas-polymeric-mark";
            }
        }
    }
    //勾稽校验标记逻辑
    if (cellMeta["custom"] && cellMeta["custom"]["beVerified"]) {
        //勾稽校验被校验项标记.cpas-be-verify-bg
        td.className = td.className + " cpas-be-verify-bg";
    }
    //校验项标记
    if (cellMeta["custom"] && cellMeta["custom"]["verify"]) {
        td.className = td.className + " cpas-verify-bg";
    }
    //试算平衡表标记
    if (cellMeta["custom"] && cellMeta["custom"]["errorMark"]) {
        td.className = td.className + " cpas-validate-error-mark";
    }
    if (cellMeta["custom"] && cellMeta["custom"]["successMark"]) {
        td.className = td.className + " cpas-validate-success-mark";
    }
}
/**
 * 文本渲染器
 * @param instance
 * @param td
 * @param row
 * @param col
 * @param prop
 * @param value
 * @param cellProperties
 */
export function cpasDefaultRender(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);
    const fontWidth = this.getTextWidth(""); //一个字符的宽度
    // const cellMeta = instance.getCellMeta(row, col);
    const cellMeta = cellProperties;
    let rVal = 0; //缩进值
    let rType = 1; // 缩进类型 , 默认首行缩进
    // let fc = cellMeta?.custom?.fc || '#000';
    // let bg = cellMeta?.custom?.bg || '#fff';
    //缩进
    if (cellMeta["custom"] && cellMeta["custom"]["r"]) {
        const rConfig = cellMeta["custom"]["r"];
        // 兼容以前的
        if (typeof rConfig === "number") {
            rVal = rConfig * fontWidth;
        }
        else {
            rVal = rConfig.val * fontWidth;
            rType = rConfig.type;
        }
    }
    // //显示值
    // let displayValue = value;
    // //数字小数位
    // if (cellMeta["custom"] && cellMeta["custom"]["dp"]) {
    //   const dp = cellMeta["custom"]["dp"];
    //   displayValue = parseFloat(value).toFixed(dp);
    // }
    if (rType === 1) {
        // 首行缩进模式
        td.style.textIndent = `${rVal}px`;
    }
    else {
        // 整行缩进模式
        td.style.paddingLeft = `${rVal + 4}px`;
    }
    commonRender.apply(this, arguments);
    //td.setAttribute("style", `text-indent:${r}px`);
    //style = `text-indent:${r}px;color:${fc}`;
}
const defaultDp = 2; //默认小数位显示
const maxDp = 4; //最大小数位阀值
const minDp = 0; //最小小数位阀值 0
/**
 * 数字渲染器`
 */
export function cpasNumericRender(instance, td, row, col, prop, value, cellProperties) {
    // const cellMeta = instance.getCellMeta(row, col);
    const cellMeta = cellProperties;
    const pattern = cellProperties.numericFormat.pattern;
    const raw_pattern = pattern.split(".");
    //TODO ps: 由于百分比在handon上实际上是一种格式化类型，而非一种数据类型。目前区分格式化类型由 pattern 暂时字符串特征进行判断
    //小数位格式需求：默认2位小数，最高位数4位，最低值为整数。即 dp = 0 为整数 ，默认无dp值的为2
    //是否为百分比
    const format_percent = pattern.includes("%");
    let dp = defaultDp;
    //是否存在dp
    if (cellMeta["custom"] && cellMeta["custom"]["dp"] !== undefined) {
        dp = cellMeta["custom"]["dp"];
        if (format_percent) {
            if (dp === 0) {
                cellProperties.numericFormat.pattern = "0%";
            }
            else {
                cellProperties.numericFormat.pattern =
                    raw_pattern[0] + "." + "0".repeat(dp) + "%";
            }
        }
        else {
            if (dp === 0) {
                cellProperties.numericFormat.pattern = "0,0";
            }
            else {
                cellProperties.numericFormat.pattern =
                    raw_pattern[0] + "." + "0".repeat(dp);
            }
        }
    }
    else {
        //默认未取到dp的地方
        // const currentDp =
        //   value && value.toString().includes(".")
        //     ? value.toString().split(".")[1].length
        //     : defaultDp;
        if (format_percent) {
            cellProperties.numericFormat.pattern =
                raw_pattern[0] + "." + "0".repeat(defaultDp) + "%"; //最少两位小数
        }
        else {
            cellProperties.numericFormat.pattern =
                raw_pattern[0] + "." + "0".repeat(defaultDp); //最少两位小数
        }
    }
    const formatValue = format_percent ? value * 100 : value;
    const bigNumber = new BigNumber(formatValue);
    const isNumber = !bigNumber.isNaN();
    let formatFixNumber = parseFloat(bigNumber.toFixed(dp));
    console.log("------------------------------------------");
    console.log(formatFixNumber);
    if (cellProperties.numericFormat.pattern === "0,0") {
        arguments[5] = Math.round(value);
    }
    // // 数值为Null的情况进行补0
    if (this.props.numberZeroReplace &&
        (value === null ||
            value === 0 ||
            value === "" ||
            value === "0" ||
            (value && isNumber && formatFixNumber === 0))) {
        arguments[5] = this.props.numberZeroReplace;
    }
    //临时增加，梦真提出的需求。百分比去掉百分比符号
    // if(value.incl)
    commonRender.apply(this, arguments);
    Handsontable.renderers.NumericRenderer.apply(this, arguments);
}
